# -*-coding:utf-8-*-
# QRCode_CN 用于生成，和解密
# QRCode_pattern 用于增强纹理
import zlib
import random
import hashlib
from codecs import register_error as register_error
import rsa
from Crypto.Cipher import AES
import pickle
import os

pubkey_path = "key/pubkey.pk"
prikey_path = "key/privkey.pk"
if os.path.exists(pubkey_path):
    pubkey = pickle.load(open(pubkey_path, "rb"))
    privkey = pickle.load(open(prikey_path, "rb"))
else:
    pubkey, privkey = rsa.newkeys(512)
    pickle.dump(pubkey, open(pubkey_path, "wb"))
    pickle.dump(privkey, open(prikey_path, "wb"))



def error_handler(error):
    if not isinstance(error, UnicodeDecodeError):
        raise error
    return "<drop>", error.end

def pad_16bytes(bytes):
    result = bytes
    length = len(bytes)
    padding_size = 16 - length % 16
    if padding_size == 16:
        padding_size = 0
    result += "\0".encode() * padding_size
    return result

random.seed(666)
k1 = "".join([random.choice("0123456789abcdef") for i in range(32)])
print("key1:\t", k1)

k2 = hashlib.md5()
k2.update(k1.encode(encoding='UTF-8'))
print("key2:\t", k2.hexdigest())
k2 = k2.hexdigest()
k3 = hashlib.md5()
k3.update(k2.encode(encoding='UTF-8'))
print("key3:\t", k3.hexdigest())
k3 = k3.hexdigest()

m1 = "1001;001;065;张三;3074bd182"  # 寄件方：单位编号；部门编号；教研室编号；姓名；电话的hex
m2 = "李四307305a42"  # 收件方：姓名；电话的hex
m3 = "091"  # 收件单位

aes1 = AES.new(str.encode(k1), AES.MODE_ECB)
aes2 = AES.new(str.encode(k2), AES.MODE_ECB)
aes3 = AES.new(str.encode(k3), AES.MODE_ECB)
c1 = aes1.encrypt(pad_16bytes(m1.encode()))

print(aes1.decrypt(c1).decode())

c2 = aes2.encrypt(pad_16bytes(m2.encode()+c1))


register_error('drop_unknown', error_handler)
result1 = aes2.decrypt(c2).decode("utf-8", "drop_unknown")
print(result1[:result1.find("<drop>")])



# c3 = rsa.encrypt(m3.encode()+c2, pubkey)
c3 = aes3.encrypt(pad_16bytes(m3.encode()+c2))
"".join([hex(int(i))[2:].rjust(2, "0") for i in c3])

with open("output/secret.txt", "wb") as f:
    f.write(c3)



with open("output/secret.output", "rb") as f:
    mmm = f.read()[:64]
# "".join([hex(i)[2:] for i in mmm])





print("解码过程")
# extract_m3 = rsa.decrypt(mmm, privkey)
extract_m3 = aes3.decrypt(mmm)
decode_m3 = extract_m3.decode("utf-8", "drop_unknown")
# print(decode_m3[:decode_m3.find("<drop>")])
print(decode_m3[:3])

# extract_m2 = aes2.decrypt(extract_m3[decode_m3.find("<drop>"):])
start_position = extract_m3.find(b"\x00")
for n in range(start_position, len(extract_m3)):
    try:
        extract_m2 = aes2.decrypt(extract_m3[3:n])
        break
    except:
        continue
decode_m2 = extract_m2.decode("utf-8", "drop_unknown")
decode_m2 = decode_m2[:decode_m2.find("<drop>")]
print(decode_m2)

extract_m1 = aes1.decrypt(extract_m2[len(decode_m2.encode()):len(decode_m2.encode())+32])
decode_m1 = extract_m1.decode("utf-8", "drop_unknown")
decode_m1 = decode_m1[:decode_m1.find("<drop>")]
print(decode_m1)